LoadModule("script/plugins/baseplugin")

CameraPlugin = baseplugin.CreatePlugin()
CameraPlugin.name = "CameraPlugin"
rawset(CameraPlugin, "__index", CameraPlugin)

function CreatePlugin()
	local inst = {}
	setmetatable(inst, CameraPlugin)
	inst.dragging = false
	inst.speed = ov.Vector3(0.0)
	return inst
end

function CameraPlugin:OnMouseMove(event)
	if not self.dragging then return end

	local vec = ov.Vector3(0)
	vec.w = 100

	local pos = event:GetPosition()
	local ofs = self.prev_mouse_pos:op_sub(pos)
	self.prev_mouse_pos = pos

	local cam = oveditor.camera
	local rect = oveditor.view.window:GetSize()
	cam:rotate(ov.Quaternion(ov.Vector3(0, 1, 0), ofs.x * 90.0 / rect:GetWidth()))
	cam:rotate(ov.Quaternion(cam.orientation.left, ofs.y * 90.0 / rect:GetHeight()))
end

function CameraPlugin:LostFocus()
	self.speed:Zero()
end

function CameraPlugin:OnRButtonDown(event)
	self.dragging = true
	self.prev_mouse_pos = event:GetPosition()
end

function CameraPlugin:OnRButtonUp(event)
	self.dragging = false
end

function CameraPlugin:Update(time)
	if not self:UpdateSpeed() then return end

	local cam = oveditor.camera
	local speed = self.speed * time
	local orient = cam.orientation
	cam.position = cam.position + orient.left * speed.x + orient.up * speed.y
end

function CameraPlugin:UpdateSpeed()
	self.speed:Zero()
	if wx.wxGetKeyState(97) or wx.wxGetKeyState(65) then
		self.speed.x = -1
	elseif wx.wxGetKeyState(68) or wx.wxGetKeyState(100) then
		self.speed.x = self.speed.x + 1 end

	if wx.wxGetKeyState(87) or wx.wxGetKeyState(119) then
		self.speed.y = 1
	elseif wx.wxGetKeyState(83) or wx.wxGetKeyState(115) then
		self.speed.y = self.speed.y - 1 end

	if self.speed:IsZero() then return false end

	self.speed:Normalize(500)
	return true
end

function CameraPlugin:OnMouseWheel(event)
	local cam = oveditor.camera
	cam.position = cam.position + 
		cam.orientation.forward * (event:GetWheelRotation() * -0.4)
end